package com.luhai.shipmentscheck.manager;

import android.hardware.Camera;
import android.util.Log;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.luhai.shipmentscheck.util.ThreadPoolProxyFactory;
import com.luhai.shipmentscheck.widget.TextureCameraPreview;

import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

/**
 * Created by jzh-创世头盔之父.
 * Date: 2019\7\30 0030* Time: 9:14
 * Emaile: 1186832904@qq.com
 * Introduction: 二维码扫描开启关闭扫描类，实现原理是CameraThread里创建一个回调接口MyPreviewCallback，不断的往接口里塞帧数据，此类实现这个接口，获取到CameraThread给的帧数据后,
 * 存在队列queue中，开启二维码扫描是此类开启线程使用zxing内的解析二维码的处理方式不断处理队列里的帧数据，有结果之后结束本次识别。
 * 注意：这里划重点，如果二维码识别不成功，极大可能是接口里的帧数据没有回调
 */
public class QRCodeManager implements TextureCameraPreview.OnStartCameraListener, Runnable {


    private static final String TAG = "QRCodeManager";

    private static volatile QRCodeManager singleTon;

    /**
     * 计时常量，30秒时间内如果没识别成功，自动结束二维码扫描
     */
    private final static int COUNT_TIME = 40;

    /**
     * 帧数据队列
     */
    private volatile Queue<MyFrame> queue = new LinkedList<>();

    private MultiFormatReader multiFormatReader;

    private Hashtable<DecodeHintType, Object> hints;

    /**
     * 是否允许添加视频帧
     */
    private boolean isEnableAddFrame = false;

    private OnQrCodeRecognizeListener onQrCodeRecognizeListener;

    @Override
    public void onPreview(byte[] data, int width, int height) {
        if (queue != null && isEnableAddFrame) {
            queue.offer(new MyFrame(data, width, height));
        }
    }

    /**
     * 识别结束回调接口
     */
    public interface OnQrCodeRecognizeListener {

        void onResult(String result);

        void onError();
    }

    public void init(OnQrCodeRecognizeListener onQrCodeRecognizeListener) {

        this.onQrCodeRecognizeListener = onQrCodeRecognizeListener;

        hints = new Hashtable<DecodeHintType, Object>(3);

        Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();
        decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
        decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);

        hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);

        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
        //hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback);

        multiFormatReader = new MultiFormatReader();
        multiFormatReader.setHints(hints);
    }

    private QRCodeManager() {

    }

    public static QRCodeManager getSingleTon() {
        if (singleTon == null) {
            synchronized (QRCodeManager.class) {
                if (singleTon == null) {
                    singleTon = new QRCodeManager();
                }
            }
        }
        return singleTon;
    }

    /**
     * 开启二维码识别
     */
    public void startQRCodeRecognize() {

        isEnableAddFrame = true;
        ThreadPoolProxyFactory.getNormalThreadPoolProxy().execute(this);
    }

    /**
     * 关闭二维码识别
     */
    public void stopQRCodeRecognize() {
        isEnableAddFrame = false;
        if (queue != null) {
            queue.clear();
        }
    }

    /**
     * 暂停二维码识别
     */
    public void pauseQRCodeRecognize() {
        isEnableAddFrame = false;
        if (queue != null) {
            queue.clear();
        }
    }

    /**
     * 继续二维码识别
     */
    public void resumeQRCodeRecognize() {
        isEnableAddFrame = true;
    }


    @Override
    public void run() {

        while (isEnableAddFrame) {
            MyFrame myFrame = queue.poll();
            if (myFrame != null) {
                decode(myFrame.data, myFrame.width, myFrame.height);
            }
        }
    }


    /**
     * 处理二维码扫描的核心方法
     *
     * @param data
     * @param width
     * @param height
     */
    private void decode(byte[] data, int width, int height) {
        if (data == null) {
            return;
        }
        long start = System.currentTimeMillis();
        Result rawResult = null;
        byte[] rotatedData = new byte[data.length];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++)
                rotatedData[x * height + height - y - 1] = data[x + y * width];
        }
        int tmp = width; // Here we are swapping, that's the difference to #11
        width = height;
        height = tmp;
        data = rotatedData;
        PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data, width, height, 0, 0, width, height, false);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        try {
            rawResult = multiFormatReader.decodeWithState(bitmap);
        } catch (ReaderException re) {
            // continue
        } finally {
            multiFormatReader.reset();
        }
        if (rawResult != null) {
            long end = System.currentTimeMillis();
            Log.d(TAG, "Found barcode (" + (end - start) + " ms):\n" + rawResult.toString());
            //识别结束暂停识别
            pauseQRCodeRecognize();
            //执行接口回调
            if (onQrCodeRecognizeListener != null) {
                onQrCodeRecognizeListener.onResult(rawResult.toString());
            }
        } else {
            Log.d(TAG, "error:解码失败");
            if (onQrCodeRecognizeListener != null) {
                onQrCodeRecognizeListener.onError();
            }
        }
    }

    /**
     * 自定义帧回调数据封装类
     */
    class MyFrame {

        protected byte[] data;
        protected int width;
        protected int height;

        public MyFrame(byte[] data, int width, int height) {
            this.data = data;
            this.width = width;
            this.height = height;
        }
    }

}
